package com.gitlab.lucky.weixin.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.gitlab.lucky.common.dao.mapper.WeixinGzhTagMapper;
import com.gitlab.lucky.common.dao.model.WeixinGzhTag;
import com.gitlab.lucky.common.enums.Constant;
import com.gitlab.lucky.common.service.ServiceImpl;
import com.gitlab.lucky.common.weixin.WeixinUtil;
import com.gitlab.lucky.weixin.web.model.Button;
import com.gitlab.lucky.weixin.web.model.TagModel;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @program: lucky
 * @author: Mr.Han
 * @create: 2018-11-05 13:13
 **/
@Service
public class WeixinTagService extends ServiceImpl<WeixinGzhTagMapper, WeixinGzhTag> {
    public static final Logger LOGGER = LoggerFactory.getLogger(WeixinTagService.class);

    @Autowired
    private WeixinUtil weixinUtil;
    private static final String CREATE_TAG_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s";
    private static final String DELETE_TAG_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=%s";

    /**
     * 创建菜单信息
     */
    public Boolean createTag(Integer platform) {
        String tagJSON = getTagJSON(platform);
        System.out.println(tagJSON);
        if (tagJSON != null) {
            String url = String.format(CREATE_TAG_URL, weixinUtil.getAccessToken(platform));
            String result = HttpUtil.post(url, tagJSON);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (jsonObject.get("errmsg").equals("ok")) {
                return true;
            } else {
                LOGGER.error(jsonObject.toJSONString());
            }
        }
        return false;
    }

    /**
     * 获取数据库菜单配置
     * @param platform
     * @return
     */
    public String getTagJSON(Integer platform) {
        try {
            Example example1 = new Example(WeixinGzhTag.class);
            example1.createCriteria().andEqualTo("platform", platform).andEqualTo("isDelete", Constant.FALSE);
            example1.orderBy("sort").asc();
            List<WeixinGzhTag> weixinGzhTags = this.selectByExample(example1);
            TagModel tagModel = new TagModel();
            List<Button> parentButton = new ArrayList<>();
            //查询父菜单
            for (WeixinGzhTag weixinGzhTag : weixinGzhTags) {
                if (weixinGzhTag.getButton() != null) {
                    Button b = new Button();
                    if (weixinGzhTag.getWxKey() != null) {
                        b.setKey(weixinGzhTag.getWxKey());
                    }
                    if (weixinGzhTag.getName() != null) {
                        b.setName(weixinGzhTag.getName());
                    }
                    if (weixinGzhTag.getType() != null) {
                        b.setType(weixinGzhTag.getType());
                    }
                    if (weixinGzhTag.getWxUrl() != null) {
                        b.setUrl(weixinGzhTag.getWxUrl());
                    }
                    if (weixinGzhTag.getWxAppid() != null) {
                        b.setAppid(weixinGzhTag.getWxAppid());
                    }
                    if (weixinGzhTag.getWxPagepath() != null) {
                        b.setPagepath(weixinGzhTag.getWxPagepath());
                    }
                    //通过父菜单查询子菜单
                    Example example = new Example(WeixinGzhTag.class);
                    example.createCriteria().
                            andEqualTo("subButton", weixinGzhTag.getButton()).
                            andEqualTo("platform", platform)
                            .andEqualTo("isDelete",Constant.FALSE);
                    List<WeixinGzhTag> weixinGzhTags1 = this.selectByExample(example);
                    List<Button> sonButton = new ArrayList<>();
                    for (WeixinGzhTag gzhTag : weixinGzhTags1) {
                        Button c = new Button();
                        if (gzhTag.getWxKey() != null) {
                            c.setKey(gzhTag.getWxKey());
                        }
                        if (gzhTag.getName() != null) {
                            c.setName(gzhTag.getName());
                        }
                        if (gzhTag.getType() != null) {
                            c.setType(gzhTag.getType());
                        }
                        if (gzhTag.getWxUrl() != null) {
                            c.setUrl(gzhTag.getWxUrl());
                        }
                        if (gzhTag.getWxAppid() != null) {
                            c.setAppid(gzhTag.getWxAppid());
                        }
                        if (gzhTag.getWxPagepath() != null) {
                            c.setPagepath(gzhTag.getWxPagepath());
                        }
                        sonButton.add(c);
                    }
                    //子菜单放到父菜单中
                    b.setSub_button(sonButton.toArray());
                    parentButton.add(b);
                }
            }
            tagModel.setButton(parentButton.toArray());
            return JSONObject.toJSONString(tagModel);
        } catch (Exception e) {
            LOGGER.error("error", e);
            return null;
        }
    }

    /**
     * 删除菜单
     * @param platform
     * @return
     */
    public boolean deleteTag(Integer platform) {
        String url = String.format(DELETE_TAG_URL, weixinUtil.getAccessToken(platform));
        String result = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.get("errmsg").equals("ok");
    }
}
